package com.pb.camera.more.detail;

import com.pb.camera.R;
import com.pb.camera.constants.MyContants;
import com.pb.camera.manager.EventManager;
import com.pb.camera.utils.Logger;
import com.pb.camera.utils.TaskHelper;
import com.pb.camera.utils.TaskHelper.Task;
import com.pb.camera.view.MyCheckBox;
import com.pb.camera.work.ControlTask;
import com.tutk.IOTC.AVIOCTRLDEFs;

import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Observable;

public class ShowSetFragment extends BaseSetFragment implements
        OnSeekBarChangeListener, View.OnClickListener {
    protected static final String TAG = "ShowSetFragment";

    private View mRootView;

    private int mContrastRatio;// 对比度
    private int mBrightness;
    private int mSaturability; // 饱和度
    private int mSharpen;
    private boolean mIsRevert;
    private boolean mIsMirror;

    private SeekBar mCRSeekBar;
    private SeekBar mBriSeekBar;
    private SeekBar mSatSeekBar;
    private SeekBar mShaSeekBar;
    private MyCheckBox mCBRevert;
    private MyCheckBox mCBMirror;
    private MyCheckBox mCBNight;

    private MyCheckedListener mMyCheckedListener;
    private PopupMenu popupMenu;
    private LinearLayout mLvEvn;
    private TextView mTVEvn;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mRootView = inflater.inflate(R.layout.fragment_show_set, container,
                false);
        super.onCreateView(inflater, container, savedInstanceState);
        return mRootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        initData();
    }

    @Override
    protected void initView() {
        mCRSeekBar = (SeekBar) mRootView.findViewById(R.id.sb_contrast_ratio);
        mBriSeekBar = (SeekBar) mRootView.findViewById(R.id.sb_brightness);
        mSatSeekBar = (SeekBar) mRootView.findViewById(R.id.sb_saturability);
        mShaSeekBar = (SeekBar) mRootView.findViewById(R.id.sb_sharpen);
        mCBMirror = (MyCheckBox) mRootView.findViewById(R.id.cb_mirror);
        mCBRevert = (MyCheckBox) mRootView.findViewById(R.id.cb_revert);
        mTVEvn = (TextView)mRootView.findViewById(R.id.tv_environment);
        mLvEvn = (LinearLayout)mRootView.findViewById(R.id.lv_env);
    }

    public void initData() {
        if (isInited)
            return;
        // TODO:从网络读取用户的配置，
        progressDialog.show();
        TaskHelper.exec(new Task() {
            boolean result;

            @Override
            public void execute() throws Exception {
                result = ControlTask.getVideoMode(0);
                ControlTask.getEnviroment(0);
                ControlTask.GetVideoSet(0);
                ControlTask.getResolution(0);
            }

            @Override
            public void callback(Exception e) {
                if (!result)
                    Toast.makeText(getActivity(), R.string.get_failed, Toast.LENGTH_SHORT).show();
                Logger.d(TAG, result ? "Success" : "Failed");
            }
        });
        isInited = true;
    }

    protected void initListener() {
        mMyCheckedListener = new MyCheckedListener();
        mCBMirror.setOnCheckedChangeListener(mMyCheckedListener);
        mCBRevert.setOnCheckedChangeListener(mMyCheckedListener);
        mCRSeekBar.setOnSeekBarChangeListener(this);
        mLvEvn.setOnClickListener(this);
    }

    @Override
    public void update(Observable observable, final Object data) {
        if (data instanceof EventManager.InitFallEvent && isIniting)
            initData();
        if (data instanceof AVIOCTRLDEFs.SMsgAVIoctrlGetVideoModeResp) {
            switch (((AVIOCTRLDEFs.SMsgAVIoctrlGetVideoModeResp) data).mode) {
                case AVIOCTRLDEFs.AVIOCTRL_VIDEOMODE_FLIP:
                    mCBRevert.setUnListenChecked(true);
                    break;
                case AVIOCTRLDEFs.AVIOCTRL_VIDEOMODE_MIRROR:

                    mCBMirror.setUnListenChecked(true);
                    break;
            }

        }
        if (data instanceof AVIOCTRLDEFs.SMsgAVIoctrlGetEnvironmentResp) {
            switch (((AVIOCTRLDEFs.SMsgAVIoctrlGetEnvironmentResp) data).mode){
                case AVIOCTRLDEFs.AVIOCTRL_ENVIRONMENT_NIGHT:
                    mTVEvn.setText(R.string.night_optimization);
                    break;
                case AVIOCTRLDEFs.AVIOCTRL_ENVIRONMENT_INDOOR_50HZ:
                    mTVEvn.setText(R.string.room_normal);
                    break;
                case AVIOCTRLDEFs.AVIOCTRL_ENVIRONMENT_INDOOR_60HZ:
                    mTVEvn.setText(R.string.room_streng);
                    break;
                case AVIOCTRLDEFs.AVIOCTRL_ENVIRONMENT_OUTDOOR:
                    mTVEvn.setText(R.string.outroom);
                    break;
            }
        }
        if (data instanceof AVIOCTRLDEFs.SMsgAVIoctrlSetVideoModeResp) {
            progressDialog.dismiss();
            if (((AVIOCTRLDEFs.SMsgAVIoctrlSetVideoModeResp) data).result != 0)
                Toast.makeText(getActivity(), R.string.set_failed, Toast.LENGTH_SHORT).show();
        }
        if (data instanceof AVIOCTRLDEFs.ACCESS_OTA_DEVICE_SET_CONFIG_INFO) {
            progressDialog.dismiss();
            setIsInited(true);
            TaskHelper.exec(new Task() {
                @Override
                public void execute() throws Exception {
                    String info = ((AVIOCTRLDEFs.ACCESS_OTA_DEVICE_SET_CONFIG_INFO) data).detail;
                    String[] infos = info.split(";");
                    int targetPosition = infos.length - 1;
                    while (targetPosition-- > 0 && !infos[targetPosition].contains("sharpness")) ;
                    mSharpen = Integer.parseInt(infos[targetPosition--].split("=")[1]);
                    mContrastRatio = Integer.parseInt(infos[targetPosition--].split("=")[1]);
                    mSaturability = Integer.parseInt(infos[targetPosition--].split("=")[1]);
                    mBrightness = Integer.parseInt(infos[targetPosition--].split("=")[1]);
                }

                @Override
                public void callback(Exception e) {
                    mSatSeekBar.setProgress(mSaturability);
                    mCRSeekBar.setProgress(mContrastRatio);
                    mBriSeekBar.setProgress(mBrightness);
                    mShaSeekBar.setProgress(mSharpen);
                }
            });
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.lv_env:{
                popupMenu = new PopupMenu(getContext(),mRootView.findViewById(R.id.iv_set_env));
                popupMenu.show();
                Menu menu = popupMenu.getMenu();
                menu.add(0, 0, 0, R.string.room_normal);
                menu.add(0, 1, 1, R.string.room_streng);
                menu.add(0, 2, 2, R.string.outroom);
                menu.add(0, 3, 3, R.string.night_optimization);
                popupMenu.show();
                popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(final MenuItem item) {
                        TaskHelper.exec(new Runnable() {
                            @Override
                            public void run() {
                                ControlTask.setEnviroment(0,(byte)item.getItemId());
                            }
                        });
                        return true;
                    }
                });
            }break;
        }
    }

    class MyCheckedListener implements OnCheckedChangeListener {

        @Override
        public void onCheckedChanged(CompoundButton buttonView,
                                     final boolean isChecked) {
            //FIXME:这个变量需要做初始化，这里只做测试使用
            byte modle = 0;
            switch (buttonView.getId()) {
                case R.id.cb_mirror:
                    mIsMirror = isChecked;
                    if (isChecked) {
                        setAVMode(0, (byte) AVIOCTRLDEFs.AVIOCTRL_VIDEOMODE_MIRROR);
                    } else if (!mCBRevert.isChecked()) {
                        setAVMode(0, (byte) AVIOCTRLDEFs.AVIOCTRL_VIDEOMODE_NORMAL);
                    }
                    break;
                case R.id.cb_revert:
                    mIsRevert = isChecked;
                    if (isChecked) {
                        setAVMode(0, (byte) AVIOCTRLDEFs.AVIOCTRL_VIDEOMODE_FLIP);
                    } else if (!mCBMirror.isChecked()) {
                        setAVMode(0, (byte) AVIOCTRLDEFs.AVIOCTRL_VIDEOMODE_NORMAL);
                    }
                    break;
                default:
                    break;
            }

        }

        private void setAVMode(final int avIndex, final byte model) {
            progressDialog.show();
            TaskHelper.exec(new Task() {
                @Override
                public void execute() throws Exception {
                    ControlTask.setVideoMode(avIndex, model);
                }

                @Override
                public void callback(Exception e) {
                }
            });
        }
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress,
                                  boolean fromUser) {
    }

    private void uploadAvSet(int i, final String name, final int value) {
        TaskHelper.exec(new Runnable() {
            @Override
            public void run() {
                ControlTask.upLoadAvSet(0, name, value);
            }
        });
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        int progress = seekBar.getProgress();
        switch (seekBar.getId()) {
            case R.id.sb_contrast_ratio:
                mContrastRatio = progress;
                uploadAvSet(0, MyContants.CONTRAST, progress);
                break;
            case R.id.sb_saturability:
                mSaturability = progress;
                uploadAvSet(0, MyContants.SATURATION, progress);
                break;
            case R.id.sb_brightness:
                mBrightness = progress;
                uploadAvSet(0, MyContants.BRIGHTNESS, progress);
                break;
            case R.id.sb_sharpen:
                mSharpen = progress;
                uploadAvSet(0, MyContants.SHARPNESS, progress);
                break;
            default:
                break;
        }
    }

}
